package com.jsyxdl.k3cloud.listener.handling;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.pdm.common.model.vo.BusinessObjectVO;
import com.hustcad.plm.pdm.common.model.vo.iteration.CommonIteratorVO;
import com.hustcad.plm.pdm.common.util.CommonUtil;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowObject;
import com.hustcad.plm.pdm.iba.mapper.TyplmStringDefMapper;
import com.hustcad.plm.pdm.iba.mapper.TyplmStringValueMapper;
import com.hustcad.plm.pdm.iteration.service.TyplmIterationService;
import com.hustcad.plm.pdm.partbom.controller.TyplmPartController;
import com.hustcad.plm.pdm.partbom.dto.ModifyPartDTO;
import com.hustcad.plm.pdm.partbom.service.TyplmPartBomService;
import com.hustcad.plm.pdm.partbom.vo.PartDetailsVO;
import com.jsyxdl.k3cloud.listener.K3CloudHttpService;
import com.jsyxdl.k3cloud.service.ErpWorkedTaskService;
import com.jsyxdl.k3cloud.service.WorkedTaskService;
import com.jsyxdl.k3cloud.utils.HttpMethodEnum;
import com.jsyxdl.k3cloud.utils.PlmPartOptionUtils;
import com.jsyxdl.k3cloud.utils.SendErpDataUtils;
import com.jsyxdl.service.ErpK3cloudService;
import com.jsyxdl.service.impl.ErpK3cloudServiceImpl;
import com.ty.basic.entity.attribute.StringDefDO;
import com.ty.basic.entity.attribute.StringValueDO;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.exception.message.SystemErrorCodeEnum;

import java.math.BigInteger;
import java.sql.Connection;
import java.util.*;

/**
 * 物料处理服务
 */
public class MaterialsHandling {

    public JSONObject productionCall(String check,Map<String, Object> executionType, FlowObject flowObject) throws Exception {


        K3CloudHttpService k3CloudHttpService = SpringUtil.getBean(K3CloudHttpService.class);
        PlmPartOptionUtils plmPartOptionUtils = SpringUtil.getBean(PlmPartOptionUtils.class);
        String code = (String) executionType.get("code");
        String k3cloud = (String) executionType.get("k3cloud");

        TyplmPartBomService typlmPartBomService = SpringUtil.getBean(TyplmPartBomService.class);
        if (typlmPartBomService != null) {
            BigInteger coid = flowObject.getRefObjectOid();
            String coType = flowObject.getRefObjectOtype();
            PartDetailsVO partDetails = plmPartOptionUtils.getPartDetailsVO(coid, coType);
            executionType.put("plm_code",partDetails.getIdentifierDisplayName());


            JSONObject voJson = JSONObject.parseObject(JSONObject.toJSONString(partDetails));
            ErpK3cloudService erpK3cloudService = SpringUtil.getBean(ErpK3cloudService.class);

            List<Map<String, Object>> baseCodeList = erpK3cloudService.getBaseCode(partDetails.getClassId());
            if (baseCodeList != null && baseCodeList.size() > 0) {
                voJson.put("baseClassificationCode", baseCodeList.get(0).get("objectnumber"));
            }
            List<Map<String, Object>> options = k3CloudHttpService.getOptions(code, k3cloud);
            Map<String, Object> inMap = k3CloudHttpService.getInTreeMap(code, k3cloud);
            Map<String, Object> bomKeyValue = new HashMap<>();

            Map<String, Object> partKey = new HashMap<>();
            for (Map<String, Object> option : options) {
                if ("类型属性".equals(option.get("plmtype"))) {
                    k3CloudHttpService.setInTree(
                            (List<Map<String, Object>>) inMap.get(option.get("plm_source_type_id")), voJson, partKey);
                    break;
                }
            }
            bomKeyValue.putAll(partKey);


            Map<String, Object> outMap = k3CloudHttpService.plmToK3CloudOut(code, k3cloud, new HashMap<>(), bomKeyValue);
            //非产成品（对应PLM里面非成品的各个类型）：
            //   启用列的“仓库”、“仓位”默认勾选
            //   启用列的“批号”根据库存标签页的“启用批号管理”联动
            //
            //产成品（对应PLM里面的成品类型）：
            //   启用列的“仓库”、“仓位”默认勾选
            //   启用列的“批号”根据库存标签页的“启用批号管理”联动
            //   影响出库成本列的“批号”根据库存标签页的“启用批号管理”联动
            //
            //其余的列、列的选项都要构建出json属性，默认不勾选
            if (!"成品".equals(partDetails.getTypeName())) {
                Object obj=outMap.get("Model");
                if(obj instanceof Map){
                    Map<String,Object> model = (Map<String,Object>) outMap.get("Model");
                    List<Map<String,Object>> fEntityInvPty = (List<Map<String,Object>>) model.get("FEntityInvPty");
                    for (int i = 0; i < fEntityInvPty.size(); i++) {
                        Map<String,Object> jsonObject = fEntityInvPty.get(i);
                        //非产品，名称叫“批号”行的“启用批号管理”列不联动
                        if (i == 3) {
                            jsonObject.put("FIsAffectCost", false);
                        }
                    }
                }
            }

            if("是".equals(check)){
                String erpOid=getErpMaterials(partDetails.getObjectNumber(),executionType);
                if(erpOid!=null){
                    Object obj=outMap.get("Model");
                    if(obj instanceof Map){
                        Map<String,Object> model = (Map<String,Object>) outMap.get("Model");
                        model.put("FMATERIALID",erpOid);
                    }
                }
            }



            JSONObject erpResult = SendErpDataUtils.sendErpDataTaskWorkder(executionType, outMap);

            JSONObject Result = erpResult.getJSONObject("Result");
            if (Result != null) {
                JSONObject ResponseStatus = Result.getJSONObject("ResponseStatus");
                if (ResponseStatus.getBooleanValue("IsSuccess") == false) {
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(
                            ResponseStatus.get("Errors").toString());
                }
            }
            else{
                if(erpResult.containsKey("messages")){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(
                            erpResult.get("messages").toString());
                }
                else if(erpResult.containsKey("Message")){
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(
                            erpResult.get("Message").toString());
                }
            }

            //构建批量审核数据，发送ERP审核BOM
            List<String> numbers = new ArrayList<>();
            numbers.add(partDetails.getObjectNumber());
            executionType.put("code","TJ000006X");
            JSONObject resultJson = SubmissionAndReviewHanding.submittReview(executionType, numbers);
            Result = resultJson.getJSONObject("Result");
            if (Result != null) {
                JSONObject ResponseStatus = Result.getJSONObject("ResponseStatus");
                if (ResponseStatus.getBooleanValue("IsSuccess") == false) {
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(
                            ResponseStatus.get("Errors").toString());
                }
            }
            return resultJson;
        }
        return null;
    }

    /**
     * 查询ERP物料信息
     * @param number
     * @param executionType
     * @return
     * @throws Exception
     */
    public String getErpMaterials(String number, Map<String, Object> executionType)
            throws Exception {
        K3CloudHttpService k3CloudHttpService = SpringUtil.getBean(K3CloudHttpService.class);

        String port = (String) executionType.get("port");
        String home = (String) executionType.get("home");

        JSONObject outMap = new JSONObject();
        outMap.put("CreateOrgId", 0);
        outMap.put("Id", "");
        outMap.put("IsSortBySeq", false);
        outMap.put("Number",number);

        //库存物料编码，库存量(基本单位),库存名称,规格型号，基本单位，库存状态

        JSONObject httpResult = new JSONObject();
        httpResult.put("IsSuccessByAPI",true);

        if (k3CloudHttpService.getCookieStr() == null) {
            Map<String, Object> login = new HashMap<>();
            login.put("acctID", SendErpDataUtils.acctID);
            login.put("lcid", 2052);
            login.put("username", SendErpDataUtils.username);
            login.put("password", SendErpDataUtils.password);
            httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                        home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",
                                                                        login);
        }
        if (httpResult.getBoolean("IsSuccessByAPI")) {
            Map<String, Object> outParameter = new HashMap<>();
            outParameter.put("formid", "BD_MATERIAL");
            outParameter.put("data", outMap);
            httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                        home + ":" + port + "/K3Cloud//Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc",
                                                                        outParameter);
            if (httpResult.containsKey("Result")) {
                JSONObject resultObj = httpResult.getJSONObject("Result");
                JSONObject responseStatus = resultObj.getJSONObject("ResponseStatus");
                if (responseStatus.getBooleanValue("IsSuccess") == false) {
                    if (responseStatus.getLongValue("MsgCode") == 1) {
                        k3CloudHttpService.setCookieStr(null);
                        k3CloudHttpService.setKdserviceSessionid(null);

                        Map<String, Object> login = new HashMap<>();
                        login.put("acctID", SendErpDataUtils.acctID);
                        login.put("lcid", 2052);
                        login.put("username", SendErpDataUtils.username);
                        login.put("password", SendErpDataUtils.password);
                        httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                    home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",
                                                                                    login);
                        if (httpResult.containsKey("IsSuccess")) {
                            if (httpResult.getBoolean("IsSuccess")) {
                                httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                            home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc",
                                                                                            outParameter);
                            }

                        } else if (httpResult.containsKey("IsSuccessByAPI")) {
                            if (httpResult.getBoolean("IsSuccessByAPI")) {
                                httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                            home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc",
                                                                                            outParameter);
                            }
                        }
                    }
                }
            }
            if (httpResult != null) {
                JSONObject Result=httpResult.getJSONObject("Result");
                JSONObject ResponseStatus=Result.getJSONObject("ResponseStatus");
                if(ResponseStatus.getBooleanValue("IsSuccess")==true){
                    JSONObject ResultUser=Result.getJSONObject("Result");
                    return ResultUser.getString("Id");
                }
            }
        }
        return null;
    }
}
